#include "TextBox.h"
#include "HwndHost.h"
#include <windowsx.h>
#include <OleCtl.h>

using namespace GUIToolkit;

namespace GUIToolkit
{

	class TextBoxWnd
		: public HwndHost
	{
	protected:
		virtual LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam, bool& handled);

		virtual void OnDetach();

	public:
		TextBoxWnd(TextBox* pOwner);

	protected:
		TextBox* textbox;
	};

}

TextBoxWnd::TextBoxWnd(TextBox* pOwner) : textbox(NULL)
{
	auto root = dynamic_cast<HwndHost*>(pOwner->GetRoot());
	if(root != NULL)
	{
		auto rect = pOwner->GetRegion();
		PointF pt(rect.X, rect.Y);
		Matrix m;
		pOwner->GetTransform(&m);
		m.Invert();
		m.TransformPoints(&pt, 1);
		rect.X = pt.X;
		rect.Y = pt.Y;
		rect.Inflate(-1.0f, -3.0f);
	
		this->Create(NULL, L"Edit", root->GetHandle(), WS_CHILD, 0, &rect);
		HWND hWnd = this->GetHandle();
		Edit_SetText(hWnd, pOwner->GetText().c_str());
		Edit_SetModify(hWnd, FALSE);
		this->SendMessage(EM_SETMARGINS, EC_LEFTMARGIN | EC_RIGHTMARGIN, MAKELPARAM(2, 2));
		Edit_SetSel(hWnd, 0, -1);
		Edit_Enable(hWnd, pOwner->IsEnable());
		Edit_SetReadOnly(hWnd, pOwner->IsReadOnly());
		this->Show();
		this->SetFocus();
		textbox = pOwner;
	}
}

void TextBoxWnd::OnDetach()
{
   textbox->pWnd = NULL;
   delete this;
}

LRESULT TextBoxWnd::WndProc(UINT msg, WPARAM wParam, LPARAM lParam, bool& handled)
{
	LRESULT lRes = 0;
	if( msg == WM_KILLFOCUS )
	{
		this->Close();
	}
	else if( textbox != NULL && msg == OCM_COMMAND && GET_WM_COMMAND_CMD(wParam, lParam) == EN_CHANGE )
	{
		HWND hWnd = this->GetHandle();
		int cchLen = ::GetWindowTextLength(hWnd) + 1;
		LPTSTR pstr = static_cast<LPTSTR>(_alloca(cchLen * sizeof(TCHAR)));
		assert(pstr);
		if( pstr == NULL ) return 0;
		::GetWindowText(hWnd, pstr, cchLen);
		textbox->SetText(pstr);
	}

	return HwndHost::WndProc(msg, wParam, lParam, handled);
}



//---TextBox-------------------------
TextBox::TextBox(float x, float y, float width, float height, LPWSTR text)
	: Control(x, y, width, height, text), pWnd(NULL)
{
	//this->SetBorderColor(Color(28, 81, 128));
}

void TextBox::OnPropertyChanged(PROPERTY p)
{
	switch(p)
	{
	case PROPERTY::UI_MOUSEOVER:
		if(this->IsEnable() && this->IsMouseOver())
			::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_IBEAM)));
		break;
	case PROPERTY::UI_FOCUS:
		if(this->IsEnable())
		{
			pWnd = new TextBoxWnd(this);
		}
		break;
	}

	if(p == PROPERTY::UI_ENABLE)
	{
		auto enable = this->IsEnable();
		//this->SetBorderColor(enable ? Color(28, 81, 128) : Color(202, 200, 187));
	}
	UIElement::OnPropertyChanged(p);
}

TextBox::~TextBox(void)
{
	SafeRelease(this->pWnd);
}